package com.glodon.paas.account.web.controller;

import java.awt.image.BufferedImage;
import java.io.IOException; 

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView; 

import com.glodon.paas.account.util.captcha1.CaptchaService;
import com.glodon.paas.consts.StringConst;

@Controller
@RequestMapping("/")
public class CaptchaController {
    public static final Logger LOGGER = LoggerFactory.getLogger(CaptchaController.class);
    @Autowired
    CaptchaService captchaService;
    
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public ModelAndView captcha(
    		  @RequestParam(value = "key", required = false) String captchakey,
    		  HttpServletRequest request,
    		  HttpServletResponse response
    		  ) {
    	if(StringUtils.isBlank(captchakey)){
    		captchakey = request.getSession().getId();
    	}
    	LOGGER.debug("captchakey="+captchakey);
    	
    	// 设置响应的类型格式为图片格式
		response.setContentType("image/jpeg");
		//禁止图像缓存。
		response.setHeader("Pragma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		
		BufferedImage buffImg = captchaService.generalCaptcha(captchakey);
		try {
			ServletOutputStream out = response.getOutputStream();
			ImageIO.write(buffImg, "png", out);
			out.flush();
			out.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
        return null;
    }
    
    /**
     * js调用的
     * @param captchakey
     * @param captchaValue
     * @param model
     */
    @RequestMapping(value = "/captcha/verify", method = RequestMethod.POST)
    public void veryfy(
    		  @RequestParam(value = "captchakey", required = false) String captchakey,
    		  @RequestParam(value = "captchaValue", required = true) String captchaValue,
    		  HttpServletRequest request,
    		  ModelMap model
    		  ) { 

    	if(StringUtils.isBlank(captchakey)){
    		captchakey = request.getSession().getId();
    	}
    	
		Boolean rt = captchaService.verifyCaptcha(captchakey, captchaValue, false);
		
		if(rt == null){
			model.addAttribute(StringConst.RESULT, StringConst.FAIL);
			return;
		}
		if(rt){
			model.addAttribute(StringConst.RESULT, StringConst.TRUE);
		}else{
			model.addAttribute(StringConst.RESULT, StringConst.FALSE);
		}
    }
}
